class TopicController < ApplicationController

  before_filter :login_required, :only=>['new', 'create']

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def show
    @topic = Topic.find(params[:id])
    @forum = Forum.find(@topic.forum_id)
    @topic.update_attribute('view_count', @topic.view_count + 1)    
    @post_pages, @posts = paginate(:posts, :conditions => ["topic_id = ? ", @topic.id], :per_page => 10, :order => "created_at DESC")
  end 

  def new
    # params[:id] is the forum id to create the topic into
    @forum = Forum.find(params[:id])
    @topic = Topic.new
    @post = Post.new
  end

  def create
    @topic = Topic.new(params[:topic])
    @topic.forum_id = params[:id]
    @post = Post.new(params[:post])
    @post.name = @topic.name
    if @topic.save
      @post.topic_id = @topic.id
      @post.user_id = current_user.id
      if @post.save
        flash[:notice] = 'Topic was successfully created.'
        redirect_to :action => 'show', :id => @topic.id
      end
    else
      render :action => 'new'
    end
  end

  def edit
    @topic = Topic.find(params[:id])
    @post = Post.find(:first, :conditions => ['topic_id = ?', @topic.id])
  end

  def update
    @topic = Topic.find(params[:id])
    @post = Post.find(:first, @topic.posts)
    if @topic.update_attributes(params[:topic])
      if @post.update_attributes(params[:post])
        flash[:notice] = 'Topic was successfully updated.'
        redirect_to :action => 'show', :id => @topic
      end
    else
      render :action => 'edit'
    end
  end

  def delete
    # destroy all posts
    @topic = Topic.find(params[:id])
    @forum_id = @topic.forum_id
    @topic.destroy
    flash[:notice] = 'Topic was successfully deleted.'
    redirect_to :controller => 'forum', :action => 'show', :id => @forum_id
  end
end
